//
//  FaildViewController.m
//  HaierGMS_APP
//
//  Created by 堂堂 on 16/10/21.
//  Copyright © 2016年 堂堂. All rights reserved.
//

#import "FaildViewController.h"
#import "UIColor+Hex.h"
#import "SignViewController.h"
#import "MBProgressHUD+MJ.h"
#import "UserDefaultUtil.h"
#import "HttpReauestParam.h"
#import "AFHTTPRequestOperationManager.h"
#define ScreenHeight [[UIScreen mainScreen] bounds].size.height//获取屏幕高度，兼容性测试
#define ScreenWidth [[UIScreen mainScreen] bounds].size.width//获取屏幕宽度，兼容性测试
@interface FaildViewController ()

@property NSArray *data;
@property NSMutableArray *images;
@property NSInteger  pos;
@property UITextView *noteText;
@end

@implementation FaildViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _pos = -1;
    _images = [[NSMutableArray alloc]init];
    [self initView];
}

-(void)initView{
    _data = @[@"订单号无效",@"该订单已核销",@"核销码无效",@"用户无法提供核销码",@"签到失败，无法补发核销码",@"操作失误"];
    
    UIScrollView *content = [[UIScrollView alloc]init];
    int height = 30;
    for (int i = 0; i < _data.count; i++) {
        UIControl *control = [[UIControl alloc]initWithFrame:CGRectMake(0, height, ScreenWidth, 50)];
        control.tag = i;
        [control addTarget:self action:@selector(content_click:) forControlEvents:UIControlEventTouchUpInside];
        [content addSubview:control];
        UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(10, height, 50, 50)];
        image.contentMode = UIViewContentModeCenter;
        image.image = [UIImage imageNamed:@"faild_image1"];
        [_images addObject:image];
        [content addSubview:image];
        UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(60, height, ScreenWidth - 80, 50)];
        lab.font = [UIFont systemFontOfSize:13];
        lab.text = _data[i];
        [content addSubview:lab];
        
        height = height + 50;
        
    }
    _noteText = [[UITextView alloc]initWithFrame:CGRectMake(50, height, ScreenWidth - 100, 100)];
    [_noteText.layer setBorderWidth:1];
    [_noteText.layer setBorderColor:[UIColor blackColor].CGColor];
    _noteText.delegate = self;
    [content addSubview:_noteText];
    
    height = height + 100;
    height = height + 30;
    //提交
    UIButton *limitBtn = [[UIButton alloc]initWithFrame:CGRectMake(10, height, ScreenWidth - 20, 50)];
    limitBtn.tag = 101;
    [limitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [limitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    [limitBtn setTitle:@"提交" forState:UIControlStateNormal];
    [limitBtn setTitle:@"提交" forState:UIControlStateSelected];
    [limitBtn setBackgroundImage:[self createImageWithColor:[UIColor colorWithHexString:@"#ff7e00"]] forState:UIControlStateNormal];
    limitBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [limitBtn addTarget:self action:@selector(limitBtn) forControlEvents:UIControlEventTouchUpInside];
    [content addSubview:limitBtn];
    height = height + 50;
    
    
    content.frame = CGRectMake(0, 0, ScreenWidth, height);
    content.contentSize = CGSizeMake(ScreenWidth, height);
    [_contentView addSubview:content];
}

-(void)limitBtn{
    //提交
    if (_pos < 0 ) {
        [MBProgressHUD showError:@"请选择失败原因"];
    }else{
        NSString *note = _noteText.text;
        
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
        [dic setObject:_serviceNo forKey:@"serviceNo"];
        [dic setObject:[UserDefaultUtil getUserId] forKey:@"identifier"];
        [dic setObject:_data[_pos] forKey:@"cause"];
        [dic setObject:note forKey:@"note"];
        
        HttpReauestParam *param = [[HttpReauestParam alloc] initWithData:@"hx_fail_cause_submit" content:[self dictionaryToJson:dic] urlType:0];
        AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
        manage.responseSerializer = [AFHTTPResponseSerializer serializer];
        [MBProgressHUD showMessage:@"提交"];
        [manage POST:param.SEVICE_URL parameters:param.param success:^(AFHTTPRequestOperation *operation, id responseObject) {
           
            NSDictionary * data = [NSJSONSerialization JSONObjectWithData:operation.responseObject options:0 error:nil];
            
            [MBProgressHUD hideHUD];
            
            if ([data[@"success"] boolValue]) {
                [MBProgressHUD showSuccess:@"提交成功"];
                //成功
                UIStoryboard *story = [UIStoryboard storyboardWithName:@"App_Main" bundle:[NSBundle mainBundle]];
                SignViewController *orderSign = [story instantiateViewControllerWithIdentifier:@"sign_opp"];
                orderSign.serviceNo = _serviceNo;
                orderSign.popCount = 3;
                orderSign.hxResult = _hxResult;
                [self.navigationController pushViewController:orderSign animated:YES];
                
            }else{
                [MBProgressHUD showError:data[@"errorMsg"]];
            }
            
           
            
            
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            //核销成功
            [MBProgressHUD showMessage:@"网络连接失败"];
            
        }];
    }
}

-(void)content_click:(UIControl *)control{
    int tag = control.tag;
    if (_pos < 0 ) {
        UIImageView *imageView = _images[tag];
        imageView.image = [UIImage imageNamed:@"faild_image2"];
        _pos = tag;
    }else{
        if (_pos != tag) {
            UIImageView *imageView = _images[tag];
            imageView.image = [UIImage imageNamed:@"faild_image2"];
            
            UIImageView *imageView2 = _images[_pos];
            imageView2.image = [UIImage imageNamed:@"faild_image1"];
            
            _pos = tag;
        }
    }
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)back_click:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

-(NSString*)dictionaryToJson:(NSDictionary *)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]){ //判断输入的字是否是回车，即按下return
        //在这里做你响应return键的代码
        [_noteText resignFirstResponder];
        return NO; //这里返回NO，就代表return键值失效，即页面上按下return，不会出现换行，如果为yes，则输入页面会换行
    }
    
    return YES;
}

- (UIImage*) createImageWithColor: (UIColor*) color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage*theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    
    return theImage;
}
- (IBAction)view_touch:(id)sender {
    [self.view endEditing:YES];
}
@end
